/*
 * @Overview:   vite-proxy
 * @Author:     Zi_Jun
 * @Email:      zijun2030@163.com
 * @Date:       2020/12/3 17:13
 * @Mark:       //
 */

import { networkInterfaces } from 'os';
import dotenv from 'dotenv';
type ProxyItem = [string, string];
type ProxyList = ProxyItem[];
interface IViteEnv {
  VITE_PORT: number;
  VITE_BASE: string;
  VITE_OUTPUT_DIR: string;
  VITE_API_URL: string;
  VITE_PROXY: [string, string][];
  VITE_DROP_CONSOLE: boolean;
  VITE_DROP_DEBUGGER: boolean;
}

/**
 * 获取客户端ip地址
 */
export function getIPAddress(): string {
  const interfaces = networkInterfaces();
  for (const devName in interfaces) {
    const iFace = interfaces[devName];
    if (!iFace) return '';
    for (let i = 0; i < iFace.length; i++) {
      const alias = iFace[i];
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
        return alias.address;
      }
    }
  }
  return '';
}

/**
 * 生成反向代理，可配置多个
 */
export function createProxy(list: ProxyList = []): any {
  const result: any = {};
  for (const [prefix, target] of list) {
    result[prefix] = {
      target,
      changeOrigin: true,
      rewrite: (path: string) => path.replace(new RegExp(`^${prefix}`), ''),
    };
  }
  console.log(result);
  return result;
}

/**
 * 加载全部环境变量
 */
export function loadEnv(): IViteEnv {
  const env = process.env.NODE_ENV;
  const result: any = {};
  const envList = [`.env.${env}.local`, `.env.${env}`, '.env.local', '.env'];
  envList.forEach((e) => {
    dotenv.config({
      path: e,
    });
  });
  for (const envName of Object.keys(process.env)) {
    let realName = (process.env as any)[envName].replace(/\\n/g, '\n');
    realName = realName === 'true' ? true : realName === 'false' ? false : realName;
    if (envName === 'VITE_PORT') {
      realName = Number(realName);
    }
    if (envName === 'VITE_PROXY') {
      try {
        realName = JSON.parse(realName);
      } catch (error) {}
    }
    result[envName] = realName;
    process.env[envName] = realName;
  }
  return result;
}
